package com.youbug.system.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.youbug.system.service.ILoginService;
import com.youbug.common.vo.R;
import com.youbug.system.vo.UserInfo;
import com.youbug.system.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;

@RestController
public class LoginController {


    @Autowired
    private DefaultKaptcha kaptcha;

    @Autowired
    private ILoginService loginService;

    @PostMapping("/login")
    public R<UserInfo> login(@RequestBody UserVo user){

        UserInfo login = loginService.login(user);

        return R.ok(login);
    }

    @GetMapping("/logout")
    public R<Boolean> logout(){

        Boolean logout = loginService.logout();

        return R.ok(logout);
    }

    @GetMapping("/keepalive")
    public R<String> keepalive(){

        return R.ok("connect-alive");
    }

    @RequestMapping("/kaptcha")
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        String capText = kaptcha.createText();
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        BufferedImage bi = kaptcha.createImage(capText);
        try(ServletOutputStream out = response.getOutputStream()){
            ImageIO.write(bi, "jpg", out);
        }
    }
}
